package com.itcam.tingshu.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itcam.tingshu.account.mapper.RechargeInfoMapper;
import com.itcam.tingshu.account.mapper.UserAccountDetailMapper;
import com.itcam.tingshu.account.mapper.UserAccountMapper;
import com.itcam.tingshu.account.service.UserAccountService;
import com.itcam.tingshu.common.constant.SystemConstant;
import com.itcam.tingshu.common.execption.ItcamException;
import com.itcam.tingshu.common.result.ResultCodeEnum;
import com.itcam.tingshu.model.account.UserAccount;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcam.tingshu.model.account.UserAccountDetail;
import com.itcam.tingshu.vo.account.AccountLockResultVo;
import com.itcam.tingshu.vo.account.AccountLockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itcam.tingshu.model.account.RechargeInfo;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;
    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    /**
     * 初始化用户账户信息
     * @param userId
     */
    @Override
    public void initUserAccount(String userId) {
        // 初始化账户信息
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(Long.parseLong(userId));
        userAccount.setTotalAmount(new BigDecimal("1000")); // 账户总金额
        userAccount.setAvailableAmount(new BigDecimal("1000")); // 可用金额
        userAccount.setTotalIncomeAmount(new BigDecimal("1000")); // 总收入
        userAccountMapper.insert(userAccount);
    }

    /**
     * 检查锁定账户金额
     * @param accountLockVo
     * @return
     */
    @Override
    public AccountLockResultVo checkAndLock(AccountLockVo accountLockVo) {
        /*
            1. 使用 redis-setnx 防止重复请求,如果重复请求了，直接查询缓存数据，并返回。如果缓存没有给用户信息提示。
            2. 核对账户可用金额并锁定账户数据(悲观锁)；根据userId,锁定金额 查询账户是否符合要求
               1. 没有符合的用户，则删除锁定key，并返回信息提示
               2. 有符合的用户锁定账户金额并
                  1. 锁定失败，则删除key，并返回信息提示
                  2. 锁定成功，添加账户明细，写入user_account_detail表中
            3. 返回锁定对象 AccountLockResultVo，并将对象放入缓存中
         */
        // 声明一个锁的key
        String lockKey = "checkAndLock:" + accountLockVo.getOrderNo();
        // 声明一个数据key
        String dataKey = "account:lock:" + accountLockVo.getOrderNo();
        // 判断是否有锁的key
        Boolean reuslt = this.redisTemplate.opsForValue().setIfAbsent(lockKey, "lock", 10, TimeUnit.SECONDS);
        if (!reuslt) {
            // 当前可能查询过了，将数据放入缓存，此时需要从缓存中获取即可
            AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dataKey);
            // 判断对象是否为空
            if (accountLockResultVo != null) {
                return accountLockResultVo;
            }
        }
        // 第一次执行查询
        // select * from user_account where user_id = 26 and available_amount >= 100 and is_deleted = 0;
        int check = userAccountMapper.check(accountLockVo.getUserId(), accountLockVo.getAmount());
        // 判断
        if (check == 0) {
            // 删除锁
            this.redisTemplate.delete(lockKey);
            // 抛出异常
            throw new ItcamException(ResultCodeEnum.ACCOUNT_LESS);
        }
        //  如果有受影响行数说明有足够的余额.
        int lock = userAccountMapper.lock(accountLockVo.getUserId(), accountLockVo.getAmount());
        //  判断是否锁定成功
        if (lock == 0) {
            //  删除锁
            this.redisTemplate.delete(lockKey);
            //  抛出异常
            throw new ItcamException(ResultCodeEnum.ACCOUNT_LOCK_ERROR);
        }
        // 给对象赋值并且放入缓存
        AccountLockResultVo accountLockResultVo = new AccountLockResultVo();
        accountLockResultVo.setUserId(accountLockVo.getUserId());
        accountLockResultVo.setAmount(accountLockVo.getAmount());
        accountLockResultVo.setContent("检测与锁定");
        // 将数据写入缓存
        this.redisTemplate.opsForValue().set(dataKey, accountLockResultVo);
        // 调用方法记录上账户资金流动
        this.addUserAccountDetail(accountLockVo.getUserId(), "锁定：" + accountLockVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_LOCK, accountLockVo.getAmount(), "lock:" + accountLockVo.getOrderNo());
        // 返回数据
        return accountLockResultVo;
    }

    /**
     * 监听扣减金额
     * @param orderNo
     */
    @Override
    public void minus(String orderNo) {
        // 声音防止锁的key
        String lockKey = "miuns:" + orderNo;
        // 声音存储在换成的数据key
        String dateKey = "account:lock:" + orderNo;
        // 判断是否有重复消息的情况
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(lockKey, "lock", 10, TimeUnit.SECONDS);
        if (!result) {
            return;
        }
        // 第一次消费
        AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dateKey);
        // 判断
        if (null == accountLockResultVo) {
            // 缓存中没有数据
            return;
        }
        // 执行扣减操作
        // update user_account set total_amount = total_amount-?
        int minus = userAccountMapper.minus(accountLockResultVo.getUserId(), accountLockResultVo.getAmount());
        if (minus == 0) {
            // 删除重复key
            this.redisTemplate.delete(lockKey);
            return;
        }
        // 记录账户明细
        this.addUserAccountDetail(accountLockResultVo.getUserId(), accountLockResultVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountLockResultVo.getAmount(), orderNo);
        // 删除缓存中的扣减信息
        this.redisTemplate.delete(dateKey);
    }

    /**
     * 监听解锁金额
     * @param orderNo
     */
    @Override
    public void accountUnlock(String orderNo) {
        // 防止重复key
        String key = "unlock:" + orderNo;
        // 数据key
        String dataKey = "account:lock:" + orderNo;
        Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, "lock", 10, TimeUnit.SECONDS);
        if (!result) {
            // 重复消费了，直接停止
            return;
        }
        // 从缓存中获取数据
        AccountLockResultVo accountLockResultVo = (AccountLockResultVo) this.redisTemplate.opsForValue().get(dataKey);
        if (null == accountLockResultVo) {
            // 缓存中没有数据
            return;
        }
        // 执行解锁金额
        int unlock = userAccountMapper.unlock(accountLockResultVo.getUserId(), accountLockResultVo.getAmount());
        // 判断
        if (unlock == 0) {
            // 删除重复key
            this.redisTemplate.delete(key);
            return;
        }
        // 记录日志，删除缓存的dataKey
        this.addUserAccountDetail(accountLockResultVo.getUserId(), accountLockResultVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_UNLOCK, accountLockResultVo.getAmount(), orderNo);
        this.redisTemplate.delete(dataKey);
    }

    /**
     * 监听消息实现用户账户充值
     * @param orderNo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        // 修改充值记录状态，增加金额，记录账户明细
        RechargeInfo rechargeInfoQuery = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
        rechargeInfoQuery.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        // 根据主键更新
        rechargeInfoMapper.updateById(rechargeInfoQuery);
        // 增加账户金额
        userAccountMapper.updateAmountByUserId(rechargeInfoQuery.getUserId(), rechargeInfoQuery.getRechargeAmount());
        // 记录账户明细
        this.addUserAccountDetail(rechargeInfoQuery.getUserId(), "充值：" + rechargeInfoQuery.getRechargeAmount(), SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfoQuery.getRechargeAmount(), orderNo);
    }

    /**
     * 获取充值记录
     * @param detailPage
     * @param userId
     * @return
     */
    @Override
    public IPage<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> detailPage, Long userId) {
        return userAccountDetailMapper.selectPage(detailPage,
                new LambdaQueryWrapper<UserAccountDetail>()
                        .eq(UserAccountDetail::getUserId, userId)
                        .eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT));
    }

    /**
     * 获取消费记录
     * @param detailPage
     * @param userId
     * @return
     */
    @Override
    public IPage<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> detailPage, Long userId) {
        return userAccountDetailMapper.selectPage(detailPage,
                new LambdaQueryWrapper<UserAccountDetail>()
                        .eq(UserAccountDetail::getUserId, userId)
                        .eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS));

    }

    // ---------------------------------------------------------------------------------------------------------

    /**
     * 添加账户明细
     * @param userId
     * @param title
     * @param typeLock
     * @param amount
     * @param orderNo
     */
    private void addUserAccountDetail(Long userId, String title, String typeLock, BigDecimal amount, String orderNo) {
        // 添加数据
        UserAccountDetail userAccountDetail = new UserAccountDetail(userId, title, typeLock, amount, orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }
}
